package com.bizmda.bizsip.sample.source.controller;

import cn.hutool.json.JSONObject;
import com.bizmda.bizsip.common.BizConstant;
import com.bizmda.bizsip.common.BizMessage;
import com.bizmda.bizsip.source.Source;
import com.bizmda.bizsip.common.BizException;
import com.bizmda.bizsip.common.BizUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;

/**
 * @author 史正烨
 */
@Slf4j
@RestController
public class SampleSourceController {
    @Autowired
    private Source source;

    @PostConstruct
    public void init() {
        try {
            this.source.init("source1");
        } catch (BizException e) {
            log.error("Source1模块初始化失败！",e);
        }
    }

    @PostMapping(value = "/source1", consumes = "application/json", produces = "application/json")
    public Object doService(@RequestBody String inMessage, HttpServletResponse response) {
        BizMessage outMessage = null;
        try {
            outMessage = this.source.process(BizUtils.getBytes(inMessage));
            outMessage.setData(new String((byte[])outMessage.getData(), BizConstant.DEFAULT_CHARSET_NAME));
            return outMessage;
        } catch (BizException e) {
            return "Source API执行出错:"
                    + "\ncode:" + e.getCode()
                    + "\nmessage:" + e.getMessage()
                    + "\nextMessage:" + e.getExtMessage();
        } catch (UnsupportedEncodingException e) {
            return "Source API执行出错:"
                    + "\nmessage:" + e.getMessage();
        }
    }
}